/**
 * @author: Jone
 * @update: 2019-09-10
 * @version: 2.5
 * 支持平台：changyou(畅游) phone(手机) warframe(星际战甲) wechat(微信) cyou3(橙柚三联) changyouwg(海战世界)
 **/
'use strict';

(function (window) {
    var that,
        name = 'ja',
        version = '2.5',
        type = 0;
    if($.inArray(location.host, [
        'local-activity.changyou.com',
        'local-join-activity.changyou.com',
        'dev-activity.changyou.com',
        'test-activity.changyou.com'
    ]) !== -1) {
        alert('检测到项目使用了 ja 旧版本，请升级或使用其他版本包')
    }
    var JoinActivity = function () {
        // -----------------全局变量----------------
        this.login = this.user.login;
        this.logout = this.user.logout;
        this.share = this.wx.share;
        this.backTop = this.utils.backTop;
        this.href = this.utils.href;
        this.longmen = this.utils.longmen;
        this.glob = {
            isMobile: /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent),
            isWechat: window.navigator.userAgent.toLowerCase().match(/MicroMessenger/i) == 'micromessenger',
            isIos: /iphone|ipod|ipad/i.test(window.navigator.userAgent.toLowerCase()),
            urlWxBind: '//tlus.changyou.com/xtl/wxBind/20180910/mobile/index.html',
            isInit: false,
            arrEnable: ['app', 'activity', 'version', 'platform'],      // 必填项
            arrHost: [      // 使用 join-activity 下接口 域名
                'kzgj.cy.com'
            ],
            code: 0,                    // 初始化状态：0 初始化未完成;1 初始化完成/已登录;2 初始化完成/未登录;1106 活动未开始;1103 活动已结束;1102 活动无效;
            jsvs: undefined,            // 后台版本
            appName: undefined,         // 活动唯一标识
            cyscid: undefined,          // 来源标识
            cystid: undefined,          // 来源标识
            urlSearch: location.search, // 初始地址“？”及后边参数
            token: undefined,           // token
            userInfo: undefined,        // 用户信息
            wechatInfo: undefined,      // 微信用户信息
            activityInfo: undefined     // 活动信息
        };
        var origin = location.origin || location.protocol + '//' + location.host;
        this.options = {
            app: undefined,             // 应用 初始化必传项
            activity: undefined,        // 活动 初始化必传项
            version: undefined,         // 版本 初始化必传项
            platform: undefined,        // 平台 初始化必传项

            type: type,                 // 版本固定情况下，区分 之前/之后 项目

            isUserInit: true,           // 是否获取用户信息
            isWxLogin: false,           // 是否微信授权
            isWxInit: false,            // 是否微信初始化，开启后才能使用微信功能
            isWxDebug: false,           // 是否开启微信debug调试
            isDebug: false,             // 是否开启调试模式
            debugPath: '/test/json',    // debug 请求基础路径
            isInitAlert: true,          // 是否关闭初始化弹窗，需要自定义活动状态 设置 false
            loginType: 0,               // 登录类型，1，移动端登录窗在当前页弹出
            host: this.glob.arrHost.indexOf(location.host) !== -1
                ? location.protocol + '//join-activity.changyou.com'
                : origin,      // 接口请求域名，默认同域名
            appId: undefined,           // 微信 appId 手动添加，权重大于 init 接口的 wxId
            wxShare: undefined,         // 微信分享内容
            ele: {
                inputPhone: '.input_phone',
                inputPhoneCode: '.input_phone_code',
                btnPhone: '.btn_phone',
                btnPhoneCode: '.btn_phone_code',
                btnWxBind: '.btn_wx_bind'
            },
            style: {
                before: { background: '', 'pointer-events': 'auto' },
                after: { background: '#9c9c9c', 'pointer-events': 'none' }
            },
            ready: function() {},   // 回调函数
        };

        that = this;
    };
    JoinActivity.fn = JoinActivity.prototype = {
        // -----------------初始化----------------
        config: function(options) {
            that.glob.isInit = true;
            $.extend(this.options, options);
            if(this.admin.enable()) {
                this.admin.set();
                that.user.getToken(function(res) {
                    if(res.code === 10000) {
                        if((that.options.platform !== 'wechat' && that.glob.isWechat && that.options.isWxLogin) || that.options.platform === 'wechat') {
                            if(!that.options.isDebug) {
                                that.user.getUserInfo('wechat', function() {
                                    that.admin.manage();
                                });
                            }else {
                                that.admin.manage();
                            }
                        }else {
                            that.admin.manage();
                        }
                    }else {
                        that.admin.output();
                    }
                })
            }
        },
        // -----------权限(辅助config参数判断)----------------
        admin: {
            enable: function() {
                var isPass = true
                    , arrMust = that.glob.arrEnable;
                // 必填项
                that.utils.console(name + '-version', version);
                arrMust.forEach(function (item, index) {
                    if(!that.options[item]) {
                        alert(item + '为必填项');
                        arrMust = arrMust.concat(arrMust.splice(index, arrMust.length - index));
                        isPass = false;
                    }else {
                        that.utils.console(item, that.options[item]);
                    }
                });
                if(that.options.platform === 'wechat' && !that.glob.isWechat) {
                    alert('请在微信中访问');
                    isPass = false;
                }
                return isPass;
            },
            set: function() {
                // 登录异常判断
                var jcode = that.utils.getQueryString('jcode');
                if(jcode) {
                    var errMsg = '';
                    var paramsObj = that.utils.getParams(location.href);
                    var paramsStr = '';
                    switch (Number(jcode)) {
                        case 1001: errMsg = '登录异常'; break;
                        case 1007: errMsg = '网络繁忙'; break;
                        case 1300: errMsg = '畅游登录异常'; break;
                        case 3103: errMsg = '您的账号已封停'; break;
                        default: errMsg = '登录异常';
                    }
                    alert(errMsg);
                    delete paramsObj.jcode;
                    if(Object.keys(paramsObj).length > 0) paramsStr = '?' + $.param(paramsObj);
                    location.href = that.options.host + location.pathname + paramsStr;
                }

                var module = that.options.type === 0 ? 'client' : 'http';
                if(that.options.type === 0) that.utils.hint('ja.config 初始化配置请设置type值为1');
                that.get = that[module].get;
                that.post = that[module].post;
                that.ajax = that[module].ajax;
                that.glob.appName = that.options.app + '-' + that.options.activity + '-' + that.options.version + '-' + that.options.platform;
                var cyscid = that.utils.getQueryString('CYSCID');
                var cystid = that.utils.getQueryString('CYSTID');
                var urlSearch = that.admin.store.get('urlSearch');
                if(cyscid) that.admin.store.set('cyscid', cyscid);
                if(cystid) that.admin.store.set( 'cystid', cystid);
                if(!urlSearch) that.admin.store.set('urlSearch', location.search)
                that.glob.cyscid = that.admin.store.get('cyscid') || undefined;
                that.glob.cystid = that.admin.store.get('cystid') || undefined;
                that.glob.urlSearch = that.admin.store.get('urlSearch') || undefined;
                that.glob.params = that.utils.getParams(that.glob.urlSearch)
            },
            manage: function() {
                if(that.glob.isWechat && that.options.isWxInit) {
                    that.wx.init(function() {
                        if(that.options.wxShare) that.wx.share(that.options.wxShare);
                    })
                }
                if(that.options.isUserInit) {
                    that.user.getUserInfo(that.options.platform, that.admin.output)
                }else {
                    that.admin.output();
                }
            },
            output: function() {
                that.glob.isInit = false;
                that.options.ready(that.glob);
            },
            error: function(msg) {
                throw new Error(name + version + ': ' + msg);
            },
            store: {
                set: function(key, val) {
                    that.utils.session.set(that.glob.appName + ':' + key, val);
                },
                get: function(key) {
                    return that.utils.session.get(that.glob.appName + ':' + key);
                }
            }
        },
        // -----------------全局使用----------------
        common: {
            // 移动端初始化
            mobile: function() {
                $('input').blur(function() { window.scrollTo(0, 0) });  // 解决 H5 在输入弹框后页面留白问题
            },
            // 输出最新全局对象 glob
            glob: function() {
                return that.glob;
            },
            // 百度事件统计
            baiduEvent: function(actName, sign, action, isPcM, isTwo) {
                // isPcM, isTwo 非必填，一般不用
                if(window._hmt) {
                    var cid = that.glob.cyscid
                        , tid = that.glob.cystid
                        , remark = isTwo ? ((cid ? ('cid=' + cid) : '无cid') + '/' + (tid ? ('tid=' + tid) : '无tid')) : (that.glob.cyscid || '无');
                    if(isPcM) remark += ('/' + (that.glob.isMobile ? 'm' : 'pc'));
                    window._hmt.push(['_trackEvent', actName + sign, action + sign, remark + '/' +sign]);
                }else {
                    that.admin.error('请先添加百度统计代码');
                }
            }
        },
        // -----------------表单验证----------------
        verify: {
            reg: {
                phone: /^1[3456789]\d{9}$/,
                email: /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/,           // 邮箱
                userName: /^[a-z0-9_-]{3,16}$/,                     // 用户名
                chineseName: /^[\u4E00-\u9FA5]{2,4}$/,              // 中文姓名
            },
            // 手机号
            phone: function (val) {
                if (!val) {
                    return '请填写手机号！';
                } else if (!val.match(this.reg.phone)) {
                    return '请输入正确的手机号！';
                } else {
                    return false;
                }
            },
            // 验证码
            code: function (val) {
                if (!val) {
                    return '请填写验证码！';
                } else if (val.length !== 6) {
                    return '验证码错误！'
                } else {
                    return false;
                }
            }
        },
        // ----------------- 工具类 ----------------
        utils: {
            console: function(name, value) {
                console.log('%c ' + name + ' %c ' + value, 'color: #fff;background: #606060;border-radius: 3px 0 0 3px','color:#fff; background: #42C02E;padding-right: 5px;border-radius: 0 3px 3px 0')
            },
            hint: function(msg) {
                var _opt = {
                    name: 'warning',
                    nStyle: { color: '#ffae47',  background: '#606060' },
                    value: msg,
                    vStyle: { color: '#fff', background: '#ffae47' }
                };
                console.log('%c ' + _opt.name + ' %c ' + _opt.value,
                    'color:' + _opt.nStyle.color + ';background:' + _opt.nStyle.background + ';border-radius: 3px 0 0 3px',
                    'color:' + _opt.vStyle.color + ';background:' + _opt.vStyle.background + ';padding-right: 5px;border-radius: 0 3px 3px 0')
            },
            getQueryString: function(name) {
                var reg = new RegExp('(^|&)'+ name +'=([^&]*)(&|$)');
                var r = window.location.search.substr(1).match(reg);
                if(r != null) return  r[2]; return null;
            },
            getParams: function(url) {
                var url = url || location.href; //获取url中"?"符后的字串
                var theRequest = new Object();
                if (url.indexOf("?") != -1) {
                    var str = url.split('?')[1];
                    var strs = str.split("&");
                    for(var i = 0; i < strs.length; i++) {
                        theRequest[strs[i].split("=")[0]]=unescape(strs[i].split("=")[1]);
                    }
                }
                return theRequest;
            },
            isJSON: function(str) {
                if (typeof str == 'string') {
                    try {
                        return (typeof JSON.parse(str) == 'object' && !!obj);
                    } catch(e) {
                        return false;
                    }
                }
            },
            objDelUndefined: function(obj) {
                var json = {};
                for(var key in obj) {
                    if(obj[key]) json[key] = obj[key];
                }
                return json;
            },
            backTop: function(num, time) {
                $('html, body').animate({scrollTop: (num || 0) + 'px'}, time || 300);
            },
            isObject: function(o) {
                return (typeof o === 'object' || typeof o === 'function') && o !== null
            },
            isString: function(val) {
                return typeof val === 'string';
            },
            objType: function(val) {
                var json = {
                    '[object Object]': 'object',
                    '[object Array]': 'array',
                    '[object Number]': 'number',
                    '[object Function]': 'function',
                    '[object Null]': 'null',
                    '[object Undefined]': 'undefined',
                    '[object Boolean]': 'boolean',
                    "[object String]" : 'string'
                };
                return json[Object.prototype.toString.call(val)]
            },
            stopMove: function() {
                document.body.addEventListener('touchmove', function (e) {
                    e.preventDefault(); //阻止默认的处理方式(阻止下拉滑动的效果)
                }, {passive: false});
            },
            getTwo: function(n) {
                n = n.toString();
                return n[1] ? n : "0" + n;
            },
            iphone: function() {
                if(screen.height === 812 && screen.width === 375){
                    return "iphoneX";
                }else if(screen.height === 736 && screen.width === 414){
                    return "iphone8P";  // 6、7、8 Plus
                }else if(screen.height === 667 && screen.width === 375){
                    return "iphone8";   // 6、7、8
                }else if(screen.height === 568 && screen.width === 320){
                    return "iphone5";
                }else{
                    return "iphone4";
                }
            },
            setUrlParams: function(val) {
                var str = '?infoData=',
                    arr = [];
                for(var key in val) {
                    var value = val[key] || typeof val[key] === 'number' ? val[key] : '';
                    arr.push(key + '@@@' + encodeURIComponent(value));
                }
                return str + arr.join('@@@@');
            },
            getUrlParams: function() {
                var json = {},
                    info = that.utils.getQueryString('infoData');
                if(info) {
                    info.split('@@@@').forEach(function(item) {
                        var key = item.split('@@@')[0],
                            val = item.split('@@@')[1];
                        json[key] = decodeURIComponent(val);
                    });
                }
                return json;
            },
            formatDate: function(now) {
                now = now ? new Date(now) : new Date();
                var year = now.getFullYear();
                var month = now.getMonth() + 1;
                var date = now.getDate();
                var hour = now.getHours();
                var minute = now.getMinutes();
                var second = now.getSeconds();
                return year + "-" + this.getTwo(month) + "-" + this.getTwo(date) + " " + this.getTwo(hour) + ":" + this.getTwo(minute) + ":" + this.getTwo(second);
            },
            url_add_key: function(url, key, val){
                key = (key || 't') +'=';  //默认是"t"
                url = url || location.href;
                var reg = new RegExp(key+'\\d+');  //正则：t=1472286066028
                var timestamp = val || +new Date();
                if(url.indexOf(key) > -1){ //有时间戳，直接更新
                    return url.replace(reg,key+timestamp);
                }else{  //没有时间戳，加上时间戳
                    if(url.indexOf('\?')>-1){
                        var urlArr=url.split('\?');
                        if(urlArr[1]){
                            return urlArr[0]+'?'+key+timestamp+'&'+urlArr[1];
                        }else{
                            return urlArr[0]+'?'+key+timestamp;
                        }
                    }else{
                        if(url.indexOf('#')>-1){
                            return url.split('#')[0]+'?'+key+timestamp+location.hash;
                        }else{
                            return url+'?'+key+timestamp;
                        }
                    }
                }
            },
            href: function(url) {
                /**
                 * 兼容安卓微信浏览器，不支持location.reload方法的bug,
                 * 刷新页面给页面后面添加t_reload=时间戳，再次刷新页面删除t_reload=时间戳，重新赋值。
                 * @return {[type]} null
                 */
                function realod(){
                    var search =window.location.search;
                    var href =window.location.href;
                    href = href.replace(/&?t_reload=(\d+)/g,'')
                    window.location.href = href+(search?'&':'?')+"t_reload="+new Date().getTime()
                }
                if(!that.glob.isIos && that.glob.isWechat) {
                    // history.replaceState(null, document.title, location.href.toString().split('#')[0] + '#');
                    // location.replace('');
                    // location.replace(url);
                    realod();
                    //location.reload();//执行比较快，不能同时用location.href重置
                }else {
                    location.href = url;
                }
            },
            reload: function() {
                that.utils.href(location.href);
            },
            refresh: function() {
                location.reload();
            },
            urlAddSearch: function(url) {
                url += (that.glob.urlSearch || '');
                return !that.glob.isIos && that.glob.isWechat ? that.utils.url_add_key(url) : url;
            },
            longmen: function(obj) {
                var imgN = 'longmen_test.png';
                obj = obj || {};
                if(obj.color === 'white' || obj.color === '#fff') {
                    imgN = 'longmen_test_white.png'
                }
                $('<img />').attr('src', '//i0.cy.com/xtl/logo/' + imgN).css($.extend({
                    width: 80,
                    position: 'absolute',
                    top: 20,
                    left: 20,
                    zIndex: 10
                }, obj)).appendTo($(obj.parent || 'body'));
            },
            deepMerge: function (obj1, obj2) {
                for (var key in obj2) {
                    obj1[key] = obj1[key] && obj1[key].toString() === "[object Object]" ?
                        that.utils.deepMerge(obj1[key], obj2[key]) : obj1[key] = obj2[key];
                }
                return obj1;
            },
            debounce: function(func,wait,immediate) {
                var timeout;
                return function () {
                    var context = this;
                    var args = arguments;
                    if (timeout) clearTimeout(timeout);
                    if (immediate) {
                        var callNow = !timeout;
                        timeout = setTimeout(function() {
                            timeout = null;
                        }, wait)
                        if (callNow) func.apply(context, args)
                    }
                    else {
                        timeout = setTimeout(function(){
                            func.apply(context, args)
                        }, wait);
                    }
                }
            },
            // 弹窗
            win: {
                scrolling: 'no',
                //是否显示滚动条 no,yes,auto
                int: function () {
                    $("#winClose").on('mouseenter',
                        function () {
                            $(this).css("background-image", "url()");
                        });
                    $("#winClose").on('mouseleave',
                        function () {
                            $(this).css("background-image", "url()");
                        });
                    $("#winClose").on('click',
                        function () {
                            $("#mask,#maskTop").fadeOut(function () {
                                $(this).remove();
                            });
                        });
                },
                open: function (width, height, src) {
                    var iframeHeight = height;
                    var marginLeft = width / 2;
                    var marginTop = height / 2;
                    var inntHtml = '';
                    inntHtml += '<div id="mask" style="width:100%; height:100%; position:fixed; top:0; left:0; z-index:1999;background:#cccccc; filter:alpha(opacity=50); -moz-opacity:0.5; -khtml-opacity: 0.5; opacity:0.5;"></div>';
                    inntHtml += '<div id="maskTop" style="width: ' + width + 'px; height: ' + height + 'px;  color: #333; position: fixed; top: 50%; left: 50%; margin-left: -' + marginLeft + 'px; margin-top: -' + marginTop + 'px; z-index: 2999; ">';
                    inntHtml += '<div id="maskTitle" style="height: 0;position: relative;">';
                    inntHtml += '<div id="winClose" style="width: 28px; height: 28px; cursor: pointer; position: absolute; top: -12px; right: -9px; background-image: url();"></div>';
                    inntHtml += '</div>';
                    inntHtml += '<iframe width="' + width + '" height="' + iframeHeight + '" frameborder="0" scrolling="' + this.scrolling + '" src="' + src + '"></iframe>';
                    inntHtml += '</div>';
                    $("body").append(inntHtml);
                    this.int();
                },
                close: function () {
                    $("#winClose").click();
                }
            },
            // 本地存储
            cookie: {
                get: function(cname) {
                    var name = cname + '=';
                    var ca = document.cookie.split(';');
                    for(var i=0; i<ca.length; i++) {
                        var c = ca[i];
                        while (c.charAt(0)==' ') c = c.substring(1);
                        if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
                    }
                    return '';
                },
                set: function(cname, cvalue, exdays, domain) {
                    var d = new Date();
                    d.setTime(d.getTime() + (exdays*24*60*60*1000));
                    var expires = 'expires='+d.toUTCString();
                    document.cookie = cname + '=' + cvalue + '; ' + expires + '; domain=' + domain + '; path=/';
                },
                del: function(name, domain) {
                    this.set(name, '', -1, domain);
                }
            },
            session: {
                set: function(name, value) {
                    if(Object.prototype.toString.call(value) === '[object Object]') value = JSON.stringify(value);
                    sessionStorage.setItem(name, value)
                },
                get: function(name) {
                    var value = sessionStorage.getItem(name);
                    return that.utils.isJSON(value) ? JSON.parse(value) : value;
                },
                remove: function(name) {
                    sessionStorage.removeItem(name);
                },
                clear: function() {
                    sessionStorage.clear();
                }
            }
        },
        // -----------------ajax请求----------------
        client: {
            ajax: function (type, url, variate, fun, plat) {
                switch (that.utils.objType(variate)) {
                    case 'object':
                        if(variate.header) {
                            var header = variate.header;
                            delete variate.header;
                        }
                        if(variate.contentType) {
                            var contentType = variate.contentType;
                            delete variate.contentType;
                        }
                        var params = variate;
                        break;
                    case 'function': fun = variate; break;
                    case 'string': plat = variate; break;
                    default: that.admin.error('client.ajax使用错误');
                }
                $.ajax({
                    type: type,
                    url: url + (that.options.isDebug ? '.json' : ''),
                    data: params || {},
                    dataType: 'json',
                    cache: false,
                    xhrFields: { withCredentials: true },
                    contentType: contentType,
                    headers: that.utils.objDelUndefined($.extend({
                        'Authorization': that.glob.token,
                        'APP': that.options.app,
                        'ACTIVITY': that.options.activity,
                        'VERSIONCODE': that.options.version,
                        'PLAT': plat || that.options.platform,
                        'CYSCID': that.glob.cyscid,
                        'CYSTID': that.glob.cystid
                    }, header)),
                    success: function(res) {
                        switch (Number(res.code)) {
                            // 用户未登录、登录状态检测失败
                            case 1012: case 1019:
                                that.utils.reload();
                                break;
                            // case 0: alert('网络繁忙，请稍后再试'); break;     // 未知
                            // case 1025: alert('短信登录检测失败'); break;
                            // case 1026: alert('短信自动登录检测失败'); break;
                            // case 1027: alert('微信公众号绑定登录检测失败'); break;
                            // case 1028: alert('微信活动绑定登录检测失败'); break;
                            // case 1317: alert('需要微信授权信息'); break;
                            default:
                                // fun(res)
                        }
                        fun(res)
                    }
                })
            },
            common: function(type, url, variate, fun, plat) {
                var opt = that.options;
                switch (that.utils.objType(variate)) {
                    case 'string': plat = variate; break;
                    case 'object': var data = variate; break;
                    case 'function': fun = variate; break;
                }
                var baseUrl = opt.host + (opt.isDebug ? opt.debugPath : '/' + (plat || opt.platform));
                that.client.ajax(opt.isDebug ? 'GET': type, baseUrl + url, data || {}, fun, plat);
            },
            get: function(url, variate, fun, plat) {
                that.client.common('GET',  url, variate, fun, plat);
            },
            post: function(url, variate, fun, plat) {
                that.client.common('POST', url, variate, fun, plat);
            }
        },
        http: {
            ajax: function (options) {
                if(that.options.isDebug) {
                    options.url = that.options.debugPath + options.url + '.json';
                    options.type = 'GET';
                }
                $.ajax(that.utils.deepMerge({
                    dataType: 'json',
                    cache: false,
                    xhrFields: { withCredentials: true },
                    headers: {
                        'Authorization': that.glob.token,
                        'APP': that.options.app,
                        'ACTIVITY': that.options.activity,
                        'VERSIONCODE': that.options.version,
                        'PLAT': that.options.platform,
                        'CYSCID': that.glob.cyscid,
                        'CYSTID': that.glob.cystid
                    }
                }, options))
            },
            common: function(type, url, variate, fun) {
                var data = {};
                if(typeof variate === 'function') {
                    fun = variate;
                }else {
                    data = variate;
                }
                that.http.ajax({
                    type: type,
                    url: that.options.host + url,
                    data: data,
                    success: fun
                });
            },
            get: function(url, variate, fun) {
                that.http.common('GET',  url, variate, fun);
            },
            post: function(url, variate, fun, plat) {
                that.http.common('POST', url, variate, fun);
            }
        },
        // -----------------用户业务----------------
        user: {
            url: {
                core: function() {
                    if(that.options.isDebug) {
                        return '/' + that.options.platform;
                    }else {
                        return  '/core/login/' + that.options.app + '/' + that.options.activity + '/' + that.options.version
                    }
                }
            },
            // 获取token
            getToken: function(fun) {
                that.client.get('/landing/init', function (res) {
                    if(res.code === 10000) {
                        if(that.options.isDebug) that.glob.code = 1;
                        that.glob.activityInfo = res.data.activity;
                        that.glob.token = res.data.token;
                        if(!that.options.appId) that.options.appId = res.data.activity.wxId;
                    }else {
                        that.glob.code = res.code;
                        if($.inArray(res.code, [1102, 1103, 1106]) !== -1) {
                            that.options.isInitAlert && alert(res.message);
                        }else {
                            console.log('landing/init', res);
                        }
                    }
                    fun && fun(res);
                });
            },
            // 获取验证码
            getCode: function(variate, callBack) {        // variate 类型 string、number、object、function，通过类型判断
                var codeInit = 60,
                    element = that.options.ele,
                    styleSheet = that.options.style,
                    $btnPhoneCode = $(element.btnPhoneCode),
                    $inputPhone = $(element.inputPhone),
                    phone = $inputPhone.val(),      // 手机号
                    styleBefore = styleSheet.before,     // 默认样式，可点击
                    styleAfter = styleSheet.after,   // 请求过程中、或倒计时中，不可点击
                    type = that.utils.objType(variate),
                    btnValue = $btnPhoneCode.text();    // 获取 发送验证码按钮 原内容

                switch (type) {
                    case 'number':case 'string': phone = variate; break;
                    case 'function': callBack = variate; break;
                    default: break;
                }
                if(that.verify.phone(phone)) return alert(that.verify.phone(phone));
                $btnPhoneCode.html('发送中...').css(styleAfter);
                that.client.post('/core/zhpt/sendcode', {
                    phone: phone
                }, function(res) {
                    if(callBack) return callBack(res);
                    if(res.code === 10000) {
                        $btnPhoneCode.css(styleAfter);
                        var codeNum = codeInit,
                            timer = setInterval(function() {
                                $btnPhoneCode.text(codeNum + 's');
                                if(codeNum <= 0) {
                                    $btnPhoneCode.text(btnValue).css(styleBefore);
                                    clearInterval(timer);
                                }
                                codeNum --;
                            }, 1000)
                    }else {
                        $btnPhoneCode.text(btnValue).css(styleBefore);
                        alert(res.message);
                    }
                }, 'phone');
            },
            // 手机号与验证码登陆
            loginPhone: function(variate, fun) {
                var element = that.options.ele,
                    styleSheet = that.options.style,
                    $inputPhone = $(element.inputPhone),
                    $inputPhoneCode = $(element.inputPhoneCode),
                    $btnPhone = $(element.btnPhone),
                    btnValue = $btnPhone.text(),
                    styleBefore = styleSheet.before,     // 默认样式，可点击
                    styleAfter = styleSheet.after,   // 请求过程中、或倒计时中，不可点击
                    inputInfo = { phone: $inputPhone.val(), code: $inputPhoneCode.val() };

                if(variate) {
                    if(that.utils.objType(variate) === 'function') {
                        fun = variate;
                    }else {
                        inputInfo = variate
                    }
                }

                var errorPhone = that.verify.phone(inputInfo.phone),
                    errorPhoneCode = that.verify.code(inputInfo.code);
                if(errorPhone) return alert(errorPhone);
                if(errorPhoneCode) return alert(errorPhoneCode);
                $btnPhone.text('登录中...').css(styleAfter);
                that.client.post(this.url.core() + '/phonelogin', inputInfo, function(res) {
                    if(fun) return fun(res);
                    if(res.code === 10000) {
                        that.utils.reload();
                    }else {
                        $btnPhone.text(btnValue).css(styleBefore);
                        alert(res.message)
                    }
                }, 'phone');
            },
            // 获取用户信息
            getUserInfo: function(variate, fun) {
                if(that.utils.objType(variate) === 'function') {
                    fun = variate;
                }else {
                    var plat = variate;
                }
                that.client.get('/user/info', plat, function(res) {
                    if(plat === 'wechat') {
                        if(res.code === 10000) {
                            that.glob.wechatInfo = res.data;
                            that.glob.code = 1;
                            that.glob.isWxLoginOver = true;
                        }else {
                            that.glob.code = 2;
                            that.user.login('wechat');
                        }
                    }else {
                        if(res.code === 10000) {
                            that.glob.userInfo = res.data;
                            that.glob.code = 1;
                        }else {
                            that.glob.code = 2;
                        }
                    }
                    fun && fun(that.glob.isInit ? that.glob : res);
                })
            },
            loginUrl:function(variate){
                var plat = that.utils.isString(variate) ? variate : that.options.platform
                var url = that.options.host + '/' + plat + that.user.url.core() + '?callback=' + encodeURI(location.href);
                return url;
            },
            // 登陆弹窗
            login: function(variate) {
                switch (that.glob.code) {
                    case 1: break;
                    case 2:
                        that.utils.cookie.del('CASGTC', '.changyou.com');
                        console.log(this);
                        var plat = that.utils.isString(variate) ? variate : that.options.platform
                            , url = that.user.loginUrl(variate)
                            , isMobile = that.glob.isMobile
                            , isWechat = that.glob.isWechat;
                        switch (plat) {
                            case 'warframe': case 'changyou':case 'changyouwg':     // 星际战甲、畅游平台、海战世界
                                if(isMobile) {
                                    if(that.options.loginType == 1) {
                                        that.utils.win.open(320, 550, url);
                                        if(that.glob.isMobile && that.glob.isIos) {
                                            // 监听键盘打开收起，将页面置顶，修复IOS12系统引起的错位
                                            window.onmessage = that.utils.debounce(function(event) {
                                                event.data.isReset && that.utils.backTop();
                                            }, 300, false);
                                        }
                                    }else {
                                        window.location.href = url
                                    }
                                }else {
                                    that.utils.win.open(496, 360, url)
                                }
                                break;
                            case 'cyou3':       // 橙柚
                                if(that.utils.isObject(variate)) url += '&' + $.param(variate);
                                isMobile ? window.location.href = url : that.utils.win.open(490, 470, url);
                                break;
                            case 'wechat':      // 微信
                                isWechat && (window.location.href = url);
                                break;
                            case 'phone':       // 手机号登录
                                that.user.loginPhone();
                                break;
                            default:
                                alert('暂时还没有该平台登陆功能');
                        }
                        break;
                    case 1106: that.options.isInitAlert && alert('活动未开始'); break;
                    case 1103: that.options.isInitAlert && alert('活动已结束'); break;
                    case 1102: that.options.isInitAlert && alert('活动无效'); break;
                    default:
                }
            },
            // 查询用户是否是封停账号
            userStatus: function(fun) {
                ja.client.get('/user/isBaned', function(res) {
                    fun && fun(res);
                })
            },
            // 是否绑定微信
            wxIsBind: function(fun) {
                if(that.glob.isWxLoginOver) {
                    that.client.post('/auto/isbind', 'wechat', function(res) {
                        fun && fun(res);
                    })
                }
            },
            wxAutoLogin: function(fun) {
                that.client.post('/auto/autologin', 'wechat', function(res) {
                    fun && fun(res);
                })
            },
            // 登出
            logout: function (fun) {
                fun = that.utils.objType(fun) === 'function' ? fun : undefined;
                if(that.glob.isWechat && that.options.isWxLogin && that.options.isUserInit) {   // 微信平台退出
                    that.client.post('/auto/cancel', 'wechat', function(res) {
                        if(res.code === 10000) {
                            that.user.logoutAct(fun);
                        }else {
                            alert(res.message);
                        }
                    })
                }else {
                    that.user.logoutAct(fun);
                }
            },
            logoutAct: function(fun) {
                that.client.post(this.url.core() + '/logout', function () {
                    if(['changyou', 'warframe', 'wechat', 'changyouwg'].indexOf(that.options.platform) !== -1) {
                        // 删除账号平台登陆标识，才能完全退出
                        that.utils.cookie.del('CASGTC', '.changyou.com');
                        // location.href = 'https://auth.changyou.com/logout.jsp?b=' + location.href.split("#")[0] + '&co=' + that.utils.cookie.get("CASGTC");
                    }
                    fun || that.utils.refresh();
                });
            }
        },
        // -----------------微信业务----------------
        wx: {
            // 微信初始化
            init: function(fun) {
                if(that.glob.code === 0) {
                    return that.admin.error('ja.wx.init 方法请在ja.config方法完成后调用');
                }
                if(!that.options.appId) {
                    return false;
                }
                $.getScript('https://res.wx.qq.com/open/js/jweixin-1.4.0.js', function () {
                    $.ajax({
                        url: location.origin + '/wechat/web/' + that.options.appId + '/config?_=' + Date.now(),
                        success: function(data) {
                            if(data.config) {
                                wx.config({
                                    debug: that.options.isWxDebug ,     // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
                                    appId: data.config.appId,           // 必填，公众号的唯一标识
                                    timestamp: data.config.timestamp,   // 必填，生成签名的时间戳
                                    nonceStr: data.config.nonceStr,     // 必填，生成签名的随机串
                                    signature: data.config.signature,   // 必填，签名，见附录1
                                    jsApiList: [                        // 必填，需要使用的JS接口列表，所有JS接口列表见附录2
                                        'translateVoice',           // 识别音频并返回识别结果接口
                                        'onMenuShareTimeline',      // 分享到朋友圈
                                        'onMenuShareAppMessage',    // 分享给朋友
                                        'onMenuShareQQ',            // 分享到QQ
                                        'onMenuShareQZone',         // 分享到QQ空间
                                        'onMenuShareWeibo',         // 分享到腾讯微博
                                        'hideMenuItems',            // 批量隐藏功能按钮接口
                                        'hideAllNonBaseMenuItem'    // 隐藏所有非基础按钮接口
                                    ]
                                });
                                fun && fun();
                            }else {
                                that.admin.error('微信初始化失败，config接口异常，' + data.msg);
                            }
                        }
                    });
                });
            },
            // 分享
            share: function(options) {
                var _options = {
                    type: 'link',
                    shareList: [
                        'onMenuShareTimeline',      // 分享到朋友圈
                        'onMenuShareAppMessage',    // 分享给朋友
                        'onMenuShareQQ',            // 分享到QQ
                        'onMenuShareWeibo',         // 分享到腾讯微博
                        'onMenuShareQZone'          // 分型到QQ空间
                    ]
                };
                _options = $.extend(_options, options);
                var list = _options.shareList,
                    hideList = _options.hideMenuList;
                delete _options['shareList'];
                delete _options['hideMenuList'];
                wx.ready(function() {
                    for(var i in list) {
                        var shareType = list[i];
                        if(typeof wx[shareType] === 'function') {
                            wx[shareType](_options);
                        }
                    }
                    wx.hideMenuItems({
                        menuList: hideList
                    });
                })
            }
        }
    };
    window[name] = new JoinActivity();
}(window));
